import React from 'react';
import {
  View,
  Alert,
  Pressable,
  FlatList,
  ActivityIndicator,
} from 'react-native';
import {useTranslation} from 'react-i18next';
import {deviceApi, DeviceType} from '@/services/api/deviceApi';
import Swipeable from 'react-native-gesture-handler/ReanimatedSwipeable';
import {useDispatch} from 'react-redux';
import {fetchDeviceBySn} from '@/store/slices/deviceSlice';
import {AppDispatch} from '@/store';
import Toast from '@/utils/toast';
import EmptyContent from '@/components/EmptyContent';
import {useAppTheme, Text} from 'tsun-smart-ui';
import DeviceCard from '@/components/DeviceInfo/DeviceCard';
import usePage from '@/hooks/usePage';
import eventBus from '@/utils/eventBus';

// 创建 ShimmerPlaceholder 组件

const DeviceManage = ({
  navigation,
  route: {params},
}: ReactNavigation.RootStackScreenProps<'DeviceManage'>) => {
  const {t} = useTranslation();
  const theme = useAppTheme();
  const dispatch = useDispatch<AppDispatch>();
  const {
    list: deviceList,
    dispatch: dispatchPage,
    loading,
  } = usePage(deviceApi.getStationEquipment);
  // 处理删除设备
  const handleDeleteDevice = (device: (typeof deviceList)[number]) => {
    Alert.alert(
      t('common.confirmButtonText', {defaultValue: '确认'}),
      t('sys.app.confirm.delete', {defaultValue: '确定要删除该设备吗？'}),
      [
        {
          text: t('user.logOutCancel', {defaultValue: '取消'}),
          style: 'cancel',
        },
        {
          text: t('pb.delete', {defaultValue: '删除'}),
          style: 'destructive',
          onPress: () => {
            // 这里应该调用删除设备的API
            deviceApi.unbindDevice(device.id!).then(async ({data}) => {
              if (data) {
                dispatchPage({
                  type: 'setPageNum',
                  payload: 1,
                });
                eventBus.emit('DEVICE_CHANGE');
              }
              Toast[data ? 'success' : 'error']({
                message: t(
                  data ? 'common.delSuccessText' : 'common.actionFailed',
                ),
              });
            });
          },
        },
      ],
    );
  };

  // 渲染设备项
  const renderDeviceItem = ({item}: {item: (typeof deviceList)[number]}) => {
    let isSwipingRef = false;
    // 渲染右侧滑动操作
    const renderRightActions = () => {
      return (
        <Pressable
          className=" justify-center  rounded-xl overflow-hidden"
          onPress={() => {
            handleDeleteDevice(item);
          }}>
          <View
            className="h-full w-[60] flex-center"
            style={{backgroundColor: theme.colors?.error?.primary}}>
            <Text style={{color: theme.colors?.neutral?.white}}>
              {t('pb.delete', {defaultValue: '删除'})}
            </Text>
          </View>
        </Pressable>
      );
    };

    const handleItemPress = () => {
      // 只有在没有滑动的情况下才触发点击
      if (!isSwipingRef) {
        dispatch(
          fetchDeviceBySn({
            sn: item.deviceSn,
            stationId: item.stationId!,
            deviceType: item.deviceType as DeviceType,
          }),
        ).unwrap();
        const index = params.assembleStationsWithDevices.findIndex(
          current => typeof current === 'object' && current.id === item.id,
        );
        params.setSelectedDevice(index);
        navigation.goBack();
      }
    };

    return (
      <Swipeable
        renderRightActions={renderRightActions}
        rightThreshold={40}
        onSwipeableWillOpen={() => {
          isSwipingRef = true;
        }}
        containerStyle={{
          marginBottom: 16,
        }}
        onSwipeableClose={() => {
          // 延迟重置状态，确保点击事件不会被误触
          setTimeout(() => {
            isSwipingRef = false;
          }, 100);
        }}
        onSwipeableOpen={() => {
          isSwipingRef = true;
        }}>
        <DeviceCard item={item} onPress={handleItemPress}></DeviceCard>
      </Swipeable>
    );
  };
  return (
    <View className="flex-1 px-4">
      <FlatList
        data={deviceList}
        renderItem={renderDeviceItem}
        showsVerticalScrollIndicator={false}
        keyExtractor={item => item.id?.toString() || ''}
        contentContainerStyle={{paddingVertical: 16}}
        ListEmptyComponent={
          !loading ? (
            <EmptyContent></EmptyContent>
          ) : (
            <ActivityIndicator
              color={theme.colors?.brand?.primary}
              size="large"
              className=" mt-4"></ActivityIndicator>
          )
        }
      />
    </View>
  );
};

export default DeviceManage;
